#!/bin/bash
VM_OPS_SCRIPTS_DIR="/root/xen/vm_ops_scripts"
source $VM_OPS_SCRIPTS_DIR/utils/env.bash
source $VM_OPS_SCRIPTS_DIR/start_vm/scene.bash
function clean_all_ops(){
local VM_ID=$1
LOG_MSG "destroy vm if need"
xm des vm-$VM_ID >/dev/null 2>&1
sleep 2
LOG_MSG "delete the work folder if need"
rm -rf $VMS_WORK_DIR/VM-$VM_ID >/dev/null 2>&1
}

LOG_MSG "start vm ops begin..."

if [ $# -lt 7 ]; then
    LOG_MSG  "$* parameter error";
    exit 255
fi  

VM_ID=$1
VM_MEM=$2
VM_HOSTNAME=$3
VM_PASSWD=$4
VM_OS_TYPE=$5
if [ $# = 7 ];then
	IPADDR[0]=$6
	BRIDGE[0]=$7
fi
if [ $# = 9 ];then
	IPADDR[0]=$6
        BRIDGE[0]=$7
        IPADDR[1]=$8
        BRIDGE[1]=$9
fi
VM_NAME=vm-$VM_ID
VM_DIR=VM-$VM_ID
ISO_FILE_PATH=$VMS_WORK_DIR/$VM_DIR/vm-$VM_ID-scene.iso
SYSDISK=$VMS_WORK_DIR/$VM_DIR/sysdisk


LOG_MSG "step.0 do some check ..."
if xm domid $VM_NAME
then
   LOG_MSG "$VM_NAME has exist"
	   exit 255
else
   LOG_MSG "$VM_NAME not exist , check pass"
fi


LOG_MSG "step.1 create workdir ...."
build_workdir_by_vmid $VM_ID
if [ $? -ne 0 ];then
   exit 255
fi


LOG_MSG "step.2 create duplicate image "
create_snapshot_image $SYSDISK
if [ $? -ne 0 ];then
   LOG_MSG " create snapshot image failed"
   clean_all_ops $VM_ID
   exit 255
fi


LOG_MSG "step.3 create vm config "
create_vm_conf $VM_ID $VM_MEM ${BRIDGE[@]}
if [ $? -ne 0 ];then
   LOG_MSG " create vm conf failed"
   clean_all_ops $VM_ID
   exit 255
fi

LOG_MSG "step.4 start vm"
xm cr $SYSDISK/$VM_NAME.cfg
if [ $? -ne 0 ];then
   LOG_MSG " create vm failed"
   clean_all_ops $VM_ID
   exit 255
fi

LOG_MSG "step.5 make scene for custom"

mk_scene_iso $VM_ID $VM_HOSTNAME $VM_PASSWD ${IPADDR[@]} $ISO_FILE_PATH 
if [ $? -ne 0 ];then
   LOG_MSG "build scene_iso file failed"
   clean_all_ops $VM_ID
   exit 255
fi

attach_iso_to_vm $VM_NAME $ISO_FILE_PATH
if [ $? -ne 0 ];then
   LOG_MSG "attach iso to vm failed"
   clean_all_ops $VM_ID
   exit 255
fi

notify_vm_iso_attached $VM_NAME
if [ $? -ne 0 ];then
   LOG_MSG "notify vm iso attached failed"
   detach_iso_from_vm $VM_NAME
   clean_all_ops $VM_ID
   exit 255
fi


wait_vm_scene_over $VM_NAME 
if [ $? -ne 0 ];then
   LOG_MSG "wait vm scene over failed"
   detach_iso_from_vm $VM_NAME
   #clean_all_ops $VM_ID
   exit 255
fi
detach_iso_from_vm $VM_NAME
LOG_MSG "over"
exit 0
